package com.imooc.mq;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author liansen
 * @create 06-17-23:48
 */
@Configuration
public class DelayConfig_Article {


    public static final String EXCHANGE_DELAY_ARTICLE = "exchange_delay_article";

    public static final String QUEUE_DELAY_ARTICLE = "queue_delay_article";

    public static final String DELAY_BINDING_ARTICLE = "delay.article.key";

    //创建交换机
    @Bean(EXCHANGE_DELAY_ARTICLE)
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_DELAY_ARTICLE)
                .durable(true) //持久化
                .delayed() //设置延迟特性
                .build();
    }

    //创建队列
    @Bean(QUEUE_DELAY_ARTICLE)
    public Queue queue(){
        return QueueBuilder.durable(QUEUE_DELAY_ARTICLE)
                            .build();
    }

    //创建队列和交换机的绑定关系
    @Bean
    public Binding delayBindingArticle(){
        /**
         * String destination, 目的地名称
         * DestinationType destinationType, 目的地类型
         * String exchange, 交换机名称
         * String routingKey, 路由键
         * Map<String, Object> arguments map类型参数
         * #代表0个或多个单词, 如果是*，则代表只能有一个单词
         */
        return new Binding(
                QUEUE_DELAY_ARTICLE,
                Binding.DestinationType.QUEUE,
                EXCHANGE_DELAY_ARTICLE,
                "delay.article.*",
                null
        );
    }

    //创建消息处理器,用来设置延迟的时间
    public static MessagePostProcessor setDelayTimes(Integer times){
        //匿名内部类
        return new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置持久属性
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                //设置延迟的时间, 单位毫秒
                message.getMessageProperties().setDelay(times);
                return message;
            }
        };
    }

}
